﻿using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Web.Mvc;


namespace DI
{
    public class UnityControllerFactory : DefaultControllerFactory
    {
        readonly IUnityContainer container;

        public UnityControllerFactory(IUnityContainer container)
        {
            this.container = container;
        }

        protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
                throw new ArgumentNullException("controllerType");

            if (!typeof(IController).IsAssignableFrom(controllerType))
                throw new ArgumentException(
                    string.Format("Type requested is not a controller: {0}", controllerType.Name),
                    "controllerType"
                    );

            return container.Resolve(controllerType) as IController;
        }
    }
}
